import cv2
import numpy as np


class Curve:
    def __init__(self):
        self.points = []

    def add_point(self, x, y):
        self.points.append((x, y))

    def clear_points(self):
        self.points = []

    def generate_curve(self):
        if len(self.points) < 2:
            return None

        xs = [p[0] for p in self.points]
        ys = [p[1] for p in self.points]

        curve = np.zeros((256,), dtype=np.uint8)
        curve[min(xs):max(xs) + 1] = np.interp(range(min(xs), max(xs) + 1), xs, ys).astype(np.uint8)

        return curve


class CurvesAdjustment:
    def __init__(self):
        self.red_curve = Curve()
        self.green_curve = Curve()
        self.blue_curve = Curve()
        self.rgb_curve = Curve()

    def adjust_image(self, image):
        b, g, r = cv2.split(image)
        if len(self.red_curve.points) > 1:
            r = cv2.LUT(r, self.red_curve.generate_curve())
        if len(self.green_curve.points) > 1:
            g = cv2.LUT(g, self.green_curve.generate_curve())
        if len(self.blue_curve.points) > 1:
            b = cv2.LUT(b, self.blue_curve.generate_curve())

        if len(self.rgb_curve.points) > 1:
            print(len(self.rgb_curve.points))
            rgb = cv2.merge((b, g, r))  # 合并为BGR通道
            rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2Lab)  # 转换为Lab颜色空间
            l, a, b = cv2.split(rgb)
            l = cv2.LUT(l, self.rgb_curve.generate_curve())  # 对L通道进行曲线调整
            rgb = cv2.merge((l, a, b))  # 合并为Lab图像
            rgb = cv2.cvtColor(rgb, cv2.COLOR_Lab2BGR)  # 转换回BGR颜色空间
            b, g, r = cv2.split(rgb)  # 分离通道

        # adjusted_image = cv2.merge((b, g, r))
        adjusted_image = cv2.merge((r, g, b))
        # 将OpenCV图像从BGR顺序转换为RGB顺序
        # rgb_image = cv2.cvtColor(adjusted_image, cv2.COLOR_BGR2RGB)
        return adjusted_image

#
# # 示例用法
# # 创建曲线调整对象
# curves_adjustment = CurvesAdjustment()
#
# # 添加控制点到红色通道曲线
# for i in range(0, 256):
#     curves_adjustment.red_curve.add_point(i, i + 100)
#
# # 添加控制点到RGB整体曲线
# for i in range(0, 256):
#     curves_adjustment.rgb_curve.add_point(i, i)
# # curves_adjustment.rgb_curve.add_point(0, 0)
# # curves_adjustment.rgb_curve.add_point(127, 127)
# # curves_adjustment.rgb_curve.add_point(255, 255)
#
# # 读取图像
# image = cv2.imread('../image/color.png')
#
# # 调整图像
# adjusted_image = curves_adjustment.adjust_image(image)
#
# # 显示原始图像和调整后的图像
# cv2.imshow('Original Image', image)
# cv2.imshow('Adjusted Image', adjusted_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
